package com.desktop.android

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.ItemTouchHelper
import androidx.recyclerview.widget.RecyclerView
import androidx.viewpager2.widget.ViewPager2
import com.desktop.android.data.AppInfo
import com.google.android.material.tabs.TabLayout
import com.google.android.material.tabs.TabLayoutMediator

class LauncherActivity : AppCompatActivity() {
    private lateinit var viewPager: ViewPager2
    private lateinit var tabLayout: TabLayout
    private lateinit var launcherPagerAdapter: LauncherPagerAdapter
    private val numPages = 3 // 桌面页数
    private val appsPerPage = 16 // 每页应用数量

    // 应用数据
    private val appList = mutableListOf(
        AppInfo("电话", android.R.drawable.ic_menu_call, "com.android.dialer"),
        AppInfo("信息", android.R.drawable.ic_menu_share, "com.android.mms"),
        AppInfo("相机", android.R.drawable.ic_menu_camera, "com.android.camera"),
        AppInfo("相册", android.R.drawable.ic_menu_gallery, "com.android.gallery"),
        AppInfo("浏览器", android.R.drawable.ic_menu_upload, "com.android.browser"),
        AppInfo("地图", android.R.drawable.ic_menu_mapmode, "com.android.maps"),
        AppInfo("日历", android.R.drawable.ic_menu_my_calendar, "com.android.calendar"),
        AppInfo("时钟", android.R.drawable.ic_menu_close_clear_cancel, "com.android.clock"),
        AppInfo("天气", android.R.drawable.ic_menu_week, "com.android.weather"),
        AppInfo("录音", android.R.drawable.stat_notify_voicemail, "com.android.voice"),
        AppInfo("视频", android.R.drawable.presence_video_away, "com.android.video"),
        AppInfo("邮箱", android.R.drawable.sym_action_email, "com.android.email"),
        AppInfo("笔记", android.R.drawable.stat_notify_error, "com.android.notes"),
        AppInfo("笔记2", android.R.drawable.stat_notify_error, "com.android.notes"),
        AppInfo("笔记3", android.R.drawable.stat_notify_error, "com.android.notes"),
        AppInfo("笔记4", android.R.drawable.stat_notify_error, "com.android.notes"),
        AppInfo("笔记5", android.R.drawable.stat_notify_error, "com.android.notes"),
        AppInfo("笔记6", android.R.drawable.stat_notify_error, "com.android.notes"),
        AppInfo("笔记7", android.R.drawable.stat_notify_error, "com.android.notes"),
        AppInfo("笔记8", android.R.drawable.stat_notify_error, "com.android.notes"),
        AppInfo("笔记9", android.R.drawable.stat_notify_error, "com.android.notes"),
        AppInfo("笔记10", android.R.drawable.stat_notify_error, "com.android.notes"),
        /*AppInfo("音乐", android.R.drawable.m, "com.android.music"),
        AppInfo("设置", android.R.drawable.sett, "com.android.settings"),
        AppInfo("应用商店", android.R.drawable.ic_store, "com.android.market"),
        AppInfo("计算器", android.R.drawable.ic_calculator, "com.android.calculator"),
        AppInfo("文件管理", android.R.drawable.ic_files, "com.android.files"),
        AppInfo("游戏", android.R.drawable.ic_game, "com.android.game"),
        AppInfo("翻译", android.R.drawable.tra, "com.android.translate")*/
    )

    // 底部 dock 应用
    private val dockApps = listOf(
        AppInfo("电话", android.R.drawable.ic_menu_call, "com.android.dialer"),
        AppInfo("信息", android.R.drawable.ic_menu_share, "com.android.mms"),
        AppInfo("相机", android.R.drawable.ic_menu_camera, "com.android.camera"),
        AppInfo("浏览器", android.R.drawable.ic_menu_upload, "com.android.browser")
    )

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_launcher)

        // 初始化ViewPager2
        viewPager = findViewById(R.id.viewPager)
        launcherPagerAdapter = LauncherPagerAdapter()
        viewPager.adapter = launcherPagerAdapter

        // 初始化TabLayout（页面指示器）
        tabLayout = findViewById(R.id.tabLayout)
        TabLayoutMediator(tabLayout, viewPager) { tab, position ->
            // 自定义页面指示器
        }.attach()

        // 设置TabLayout指示器样式
        for (i in 0 until numPages) {
            val tab = tabLayout.newTab()
            tab.customView = createTabIndicator(i == 0)
            tabLayout.addTab(tab)
        }

        // 监听页面变化，更新指示器
        viewPager.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() {
            override fun onPageSelected(position: Int) {
                super.onPageSelected(position)
                updateTabIndicators(position)
            }
        })

        // 初始化Dock栏
        initDock()
    }

    // 创建页面指示器
    private fun createTabIndicator(isActive: Boolean): View {
        val view = View(this)
        val params = ViewGroup.LayoutParams(
            if (isActive) 30 else 10,
            10
        )
        view.layoutParams = params
        view.setBackgroundResource(if (isActive) R.drawable.tab_indicator_active else R.drawable.tab_indicator_inactive)
        return view
    }

    // 更新页面指示器状态
    private fun updateTabIndicators(activePosition: Int) {
        for (i in 0 until tabLayout.tabCount) {
            val tab = tabLayout.getTabAt(i)
            tab?.customView = createTabIndicator(i == activePosition)
        }
    }

    // 初始化底部Dock栏
    private fun initDock() {
        val dockRecyclerView = findViewById<RecyclerView>(R.id.dockRecyclerView)
        dockRecyclerView.layoutManager =
            GridLayoutManager(this, 5, GridLayoutManager.HORIZONTAL, false)
        dockRecyclerView.adapter = DockAdapter(dockApps)
    }

    // 桌面页面适配器
    inner class LauncherPagerAdapter : RecyclerView.Adapter<LauncherPagerAdapter.PageViewHolder>() {

        inner class PageViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
            val recyclerView: RecyclerView = itemView.findViewById(R.id.pageRecyclerView)
        }

        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): PageViewHolder {
            val view = LayoutInflater.from(parent.context)
                .inflate(R.layout.launcher_page, parent, false)
            return PageViewHolder(view)
        }

        override fun onBindViewHolder(holder: PageViewHolder, position: Int) {
            // 计算当前页应显示的应用
            val startIndex = position * appsPerPage
            val endIndex = Math.min(startIndex + appsPerPage, appList.size)
            val pageApps = appList.subList(startIndex, endIndex)

            // 设置网格布局，4列
            holder.recyclerView.layoutManager = GridLayoutManager(this@LauncherActivity, 4)
            val adapter = AppGridAdapter(pageApps)
            holder.recyclerView.adapter = adapter

            // 设置拖拽功能
            val itemTouchHelper = ItemTouchHelper(AppItemTouchHelperCallback(adapter))
            itemTouchHelper.attachToRecyclerView(holder.recyclerView)
        }

        override fun getItemCount(): Int = numPages
    }

    // 应用网格适配器
    inner class AppGridAdapter(private val apps: List<AppInfo>) :
        RecyclerView.Adapter<AppGridAdapter.AppViewHolder>(),
        ItemTouchHelperAdapter {

        inner class AppViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
            val icon: ImageView = itemView.findViewById(R.id.appIcon)
            val name: TextView = itemView.findViewById(R.id.appName)
        }

        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): AppViewHolder {
            val view = LayoutInflater.from(parent.context)
                .inflate(R.layout.app_icon, parent, false)
            return AppViewHolder(view)
        }

        override fun onBindViewHolder(holder: AppViewHolder, position: Int) {
            val app = apps[position]
            holder.icon.setImageResource(app.iconRes)
            holder.name.text = app.appName

            // 应用点击事件
            holder.itemView.setOnClickListener {
                Toast.makeText(this@LauncherActivity, "打开 ${app.appName}", Toast.LENGTH_SHORT)
                    .show()
            }

            // 长按进入编辑模式（拖拽）
            holder.itemView.setOnLongClickListener {
                Toast.makeText(this@LauncherActivity, "编辑模式", Toast.LENGTH_SHORT).show()
                false
            }
        }

        override fun getItemCount(): Int = apps.size

        // 拖拽交换位置
        override fun onItemMove(fromPosition: Int, toPosition: Int) {
            // 实际项目中应该更新数据源
            notifyItemMoved(fromPosition, toPosition)
        }

        // 拖拽结束
        override fun onItemDropped() {
            // 保存新的排序
        }
    }

    // Dock栏适配器
    inner class DockAdapter(private val apps: List<AppInfo>) :
        RecyclerView.Adapter<DockAdapter.DockViewHolder>() {

        inner class DockViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
            val icon: ImageView = itemView.findViewById(R.id.dockIcon)
        }

        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): DockViewHolder {
            val view = LayoutInflater.from(parent.context)
                .inflate(R.layout.dock_icon, parent, false)
            return DockViewHolder(view)
        }

        override fun onBindViewHolder(holder: DockViewHolder, position: Int) {
            val app = apps[position]
            holder.icon.setImageResource(app.iconRes)

            holder.itemView.setOnClickListener {
                Toast.makeText(this@LauncherActivity, "打开 ${app.appName}", Toast.LENGTH_SHORT)
                    .show()
            }
        }

        override fun getItemCount(): Int = apps.size
    }

    // 拖拽回调
    inner class AppItemTouchHelperCallback(private val adapter: ItemTouchHelperAdapter) :
        ItemTouchHelper.Callback() {

        override fun getMovementFlags(
            recyclerView: RecyclerView,
            viewHolder: RecyclerView.ViewHolder
        ): Int {
            // 允许上下左右拖拽
            val dragFlags = ItemTouchHelper.UP or ItemTouchHelper.DOWN or
                    ItemTouchHelper.LEFT or ItemTouchHelper.RIGHT
            return makeMovementFlags(dragFlags, 0)
        }

        override fun onMove(
            recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder,
            target: RecyclerView.ViewHolder
        ): Boolean {
            // 通知适配器交换位置
            adapter.onItemMove(viewHolder.adapterPosition, target.adapterPosition)
            return true
        }

        override fun onSwiped(viewHolder: RecyclerView.ViewHolder, direction: Int) {
            // 我们不处理滑动删除
        }

        override fun onSelectedChanged(viewHolder: RecyclerView.ViewHolder?, actionState: Int) {
            super.onSelectedChanged(viewHolder, actionState)
            // 拖拽时高亮显示
            if (actionState == ItemTouchHelper.ACTION_STATE_DRAG) {
                viewHolder?.itemView?.alpha = 0.5f
                viewHolder?.itemView?.scaleX = 1.1f
                viewHolder?.itemView?.scaleY = 1.1f
            }
        }

        override fun clearView(recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder) {
            super.clearView(recyclerView, viewHolder)
            // 拖拽结束恢复状态
            viewHolder.itemView.alpha = 1.0f
            viewHolder.itemView.scaleX = 1.0f
            viewHolder.itemView.scaleY = 1.0f
            adapter.onItemDropped()
        }

        override fun isLongPressDragEnabled(): Boolean {
            return true // 长按启用拖拽
        }
    }

    // 拖拽接口
    interface ItemTouchHelperAdapter {
        fun onItemMove(fromPosition: Int, toPosition: Int)
        fun onItemDropped()
    }
}
